package kitread.model;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;
import java.util.LinkedList;

import kitread.util.ImageExtractor;

import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;

public class Feed extends LinkedList<FeedItem> {

	private static final long serialVersionUID = -4160373219237134064L;
	private URL url;
	private BufferedImage icon;
	private String feedTitle;
	private Boolean loaded = false;
	
	public Feed(String url) throws MalformedURLException {
		this(new URL(url));
	}
	
	public Feed(URL url) {
		this.url = url;
	}
	
	public void refresh() throws IllegalArgumentException, FeedException, IOException {
		XmlReader reader = new XmlReader(url);
		SyndFeed feed = new SyndFeedInput().build(reader);
		icon = ImageExtractor.instance().getIcon(url);
		feedTitle = feed.getTitle();
		clear();
		for (Object e : feed.getEntries()) {
			add(new FeedItem(this, (SyndEntry) e));
		}
		if (reader != null) {
			reader.close();
		}
		Collections.sort(this, FeedItemComparator.instance());
		loaded = true;
	}
	
	/**
	 * @return the loaded
	 */
	public Boolean isLoaded() {
		return loaded;
	}

	/**
	 * @return the feedTitle
	 */
	public String getFeedTitle() {
		return feedTitle;
	}
	
	/**
	 * @return the icon
	 */
	public BufferedImage getIcon() {
		return icon;
	}

	@Override
	public int hashCode() {
		return url.hashCode();
	}
}
